import { Component } from "react";

//摄氏温度和华氏温度的转换 ℃ = (F - 32) / 1.8

export default class Calculator extends Component {
    constructor(props) {
        super(props);
        this.state = {
            temperature: 0,
            type: "c",
            name: "katy"
        }
        this.changePro = this.changePro.bind(this);
        this.changeTemp = this.changeTemp.bind(this);
    }

    changeTemp(e) {
        console.log("change temp");
        this.setState({
            temperature: e.value,
            type: e.type
        })
    }

    changePro(e) {
        var name = this.state.name == "katy" ? "win7" : "katy";
        this.setState({ name });
    }

    c2f(c){
        return (c*180 - 3200)/100;
    }

    f2c(f){
        return  (f*100 - 3200) / 180;
    }

    render() {
        var type = this.state.type;
        var temp = this.state.temperature;
        var ftmp = type=="c"?this.c2f(temp):temp;
        var ctmp = type=="f"?this.f2c(temp):temp;
        console.log(ftmp);
        console.log(ctmp);
        isNaN(ftmp) && (ftmp = "");
        isNaN(ctmp) && (ctmp = "");
        return (
            <div className="M-cal">
                <h3>华氏温度：</h3>
                <FCalculator
                    temperature={ftmp}
                    change={this.changeTemp} />
                <h3>摄氏温度：</h3>
                <CCalculator temperature={ctmp} change={this.changeTemp}/>
                <div>
                    <button onClick={this.changePro}>props 变化会触发 constructor 吗?</button>
                </div>
                <div>
                    <PropT name={this.state.name} />
                </div>
            </div>
        )
    }
}


class PropT extends Component {
    constructor(props) {
        super(props);
        this.state = {
            name: props.name
        }
        console.log("PropT constructor");
    }
    render() {
        console.log("PropT render");
        return (<h4 style={{ color: 'red' }}>{this.state.name}</h4>)
    }
}


class FCalculator extends Component {
    constructor(props) {
        super(props);
        this.changeTemp = this.changeTemp.bind(this);
    }

    changeTemp(e) {
        //组件输入框值变化，触发上层事件更改值即可
        console.log("change F temp");
        var val = e.target.value;
        this.props.change({value: val, type: 'f'});
    }

    render() {
        return (
            <div className="M-FCal">
                <input value={this.props.temperature} onChange={this.changeTemp} />
            </div>
        )
    }
}

class CCalculator extends Component {
    constructor(props) {
        super(props);
        this.changeTemp = this.changeTemp.bind(this);
    }

    changeTemp(e) {
        //组件输入框值变化，触发上层事件更改值即可
        var val = e.target.value;
        this.props.change({value: val, type: 'c'});
    }

    render() {
        return (
            <div className="M-FCal">
                <input value={this.props.temperature} onChange={this.changeTemp} />
            </div>
        )
    }
}